package com.xbongbong.paas.service.log.crm.help;

import com.alibaba.dingtalk.openapi.newmessage.entity.OA;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DateTimeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.logger.ArchiveOperationLogHandle;
import com.xbongbong.parent.interfaces.logger.FocusOperationLogHandle;
import com.xbongbong.parent.interfaces.logger.OperationLogFactory;
import com.xbongbong.parent.interfaces.logger.OperationLogHandle;
import com.xbongbong.parent.interfaces.logger.PushNotifyLogHandle;
import com.xbongbong.pro.businessdata.pojo.dto.FocusDTO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.customer.pojo.dto.ChangeStatusDTO;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.domain.entity.PersonLabelEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.label.pojo.dto.PersonLabelSaveDTO;
import com.xbongbong.pro.listbatch.pojo.dto.AddLabelDTO;
import com.xbongbong.pro.listbatch.pojo.dto.ArchiveDTO;
import com.xbongbong.pro.listbatch.pojo.dto.DelRemindDTO;
import com.xbongbong.pro.log.pojo.DetailLogComplexPojo;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.log.pojo.dto.AddBatchPushNotifyDTO;
import com.xbongbong.pro.log.pojo.dto.AddFocusDTO;
import com.xbongbong.pro.log.pojo.dto.AddPushNotifyDTO;
import com.xbongbong.pro.log.pojo.dto.DeleteFocusDTO;
import com.xbongbong.pro.log.pojo.dto.DeletePushNotifyDTO;
import com.xbongbong.pro.log.pojo.dto.OperateArchiveDTO;
import com.xbongbong.pro.log.pojo.dto.UpdateOperationLogDTO;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.service.toolbox.data.ProFormDataHelp;
import com.xbongbong.pro.weblist.pojo.dto.CommunicatePlanOperateDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.CommunicatePlanEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.dictionary.CommunicatePlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PublicEnum;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author: yingjianfeng
 * @date: 2022/4/13 17:04
 * @description:操作日志帮助类
 */
@Slf4j
@Component
public class OperationLogHelp {
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    @Lazy
    private OperationLogFactory operationLogFactory;
    @Resource
    private PushModel pushModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private ProFormDataHelp proFormDataHelp;
    @Resource
    private LabelModel labelModel;
    @Resource
    private IndexTypeModel indexTypeModel;

    /**
     * 详情统一标题
     * date: 2022/6/10 10:04 上午
     * @Author yingjf
     * @param :
     */
    public static String setDetailTitle(){
        return I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_OPERATION_OBJECT);
    }

    /**
     * 新增跟进提醒
     * date: 2022/4/24 5:19 下午
     * @Author yingjf
     * @param formDataAddDTO:
     * @param oldDataList:
     * @param redundantTemplateTypeEnum:
     */
    @Async("sysLogThreadPool")
    public void addPushNotifyLog(FormDataAddDTO formDataAddDTO,JSONObject oldDataList, RedundantTemplateTypeEnum redundantTemplateTypeEnum){
        String corpid = formDataAddDTO.getCorpid();
        String loginUserName = formDataAddDTO.getLoginUserName();
        String userId = formDataAddDTO.getUserId();
        Integer isBatch = formDataAddDTO.getIsBatch();
        String httpHeader = formDataAddDTO.getHttpHeader();
        Long formId = formDataAddDTO.getFormId();
        Integer businessType = formDataAddDTO.getBusinessType();
        PushNotifyLogHandle pushNotufyLogHandle = operationLogFactory.getPushNotufyLogHandle(SaasMarkEnum.SAAS.getCode(),
                redundantTemplateTypeEnum.getCode());
        if(Objects.equals(0,isBatch)){
            // 非批量操作
             AddPushNotifyDTO addPushNotifyDTO = new AddPushNotifyDTO(corpid,userId,loginUserName,oldDataList,httpHeader,formId,businessType);
            pushNotufyLogHandle.addPushNotify(addPushNotifyDTO);
        }else{
            // 批量操作
            AddBatchPushNotifyDTO addBatchPushNotifyDTO = new AddBatchPushNotifyDTO(corpid,userId,loginUserName,oldDataList,httpHeader,formId,businessType);
            pushNotufyLogHandle.addBatchPushNotify(addBatchPushNotifyDTO);
        }
    }
    /**
     * 删除跟进提醒
     * date: 2022/4/24 5:20 下午
     * @Author yingjf
     * @param deleteRemind:
     */
    @Async("sysLogThreadPool")
    public void deletePushNotifyLog(DelRemindDTO deleteRemind){
        try {
            Long dataId = deleteRemind.getDataId();
            String corpid = deleteRemind.getCorpid();
            String userId = deleteRemind.getUserId();
            String loginUserName = deleteRemind.getLoginUserName();
            if(Objects.isNull(deleteRemind.getLoginUser())){
                return;
            }
            String httpHeader = deleteRemind.getHttpHeader();
            PushEntity pushEntity =  pushModel.getByKey(dataId.intValue(),corpid);
            Long refId = pushEntity.getRefId();
            Integer type = pushEntity.getType();

            String msg = pushEntity.getMsg();
            OA oa = JSONObject.parseObject(msg, OA.class);
            if (Objects.isNull(oa)) {
                oa = new OA();
            }
            OA.Body body = oa.getBody() == null ? new OA.Body() : oa.getBody();
            String title = body.getTitle();

            PaasFormDataEntityExt paasFormDataEntityExt = paasEsModel.getByKey(refId, corpid, IndexTypeEnum.getByCode(type), null);
            Long formId = paasFormDataEntityExt.getFormId();
            dataId = paasFormDataEntityExt.getDataId();
            String name = paasFormDataEntityExt.getName();
            DeletePushNotifyDTO deletePushNotifyDTO = new DeletePushNotifyDTO();
            deletePushNotifyDTO.setCorpid(corpid);
            deletePushNotifyDTO.setOpUserId(userId);
            deletePushNotifyDTO.setOpUserName(loginUserName);
            deletePushNotifyDTO.setOpObjectName(name);
            deletePushNotifyDTO.setHttpHeader(httpHeader);
            deletePushNotifyDTO.setOperateType(OperateTypeEnum.DELETE);
            deletePushNotifyDTO.setOpObjectId(dataId.toString());
            deletePushNotifyDTO.setFormId(formId);
            deletePushNotifyDTO.setBusinessType(type);
            deletePushNotifyDTO.setTitle(title);
            deletePushNotifyDTO.setPaasFormDataEntityExt(paasFormDataEntityExt);
            PushNotifyLogHandle pushNotufyLogHandle = operationLogFactory.getPushNotufyLogHandle(SaasMarkEnum.SAAS.getCode(),
                    type);
            if(Objects.nonNull(pushNotufyLogHandle)){
                pushNotufyLogHandle.deletePushNotify(deletePushNotifyDTO);
            }
        }catch (XbbException e){
            log.error("com.xbongbong.paas.service.log.help.OperationLogHelp.deletePushNotify",e);
        }
    }
    /**
     * 新增关注或取消关注
     * date: 2022/4/24 5:20 下午
     * @Author yingjf
     * @param :
     */
    @Async("sysLogThreadPool")
    public void addOrDeleteFocus(FocusDTO focusDTO){
        String corpid = focusDTO.getCorpid();
        Integer businessType = focusDTO.getBusinessType();
        Long dataId = focusDTO.getDataIdList().get(0);
        Long formId = focusDTO.getFormId();
        String userId = focusDTO.getUserId();
        String loginUserName = focusDTO.getLoginUserName();

        FocusOperationLogHandle focusLogHandle = operationLogFactory.getFocusLogHandle(SaasMarkEnum.SAAS.getCode(), businessType);
        Integer focus = focusDTO.getFocus();
        if(Objects.equals(1,focus)){
            AddFocusDTO addFocusDTO = new AddFocusDTO();
            addFocusDTO.setCorpid(corpid);
            addFocusDTO.setBusinessType(businessType);
            addFocusDTO.setDataId(dataId);
            addFocusDTO.setFormId(formId);
            addFocusDTO.setOpObjectId(dataId.toString());
            addFocusDTO.setOpUserId(userId);
            addFocusDTO.setOpUserName(loginUserName);
            focusLogHandle.add(addFocusDTO);
        }else{
            DeleteFocusDTO deleteFocusDTO = new DeleteFocusDTO();
            deleteFocusDTO.setCorpid(corpid);
            deleteFocusDTO.setBusinessType(businessType);
            deleteFocusDTO.setDataId(dataId);
            deleteFocusDTO.setFormId(formId);
            deleteFocusDTO.setOpObjectId(dataId.toString());
            deleteFocusDTO.setOpUserId(userId);
            deleteFocusDTO.setOpUserName(loginUserName);
            focusLogHandle.delete(deleteFocusDTO);
        }
    }

    /**
     * 获取对象值
     * date: 2022/4/25 9:45 上午
     * @Author yingjf
     * @param xbbRefTypeEnum:
     * @param data:
     */
    public static String getName(XbbRefTypeEnum xbbRefTypeEnum, JSONObject data)throws XbbException{
        return RuleBusinessLogger.getName(xbbRefTypeEnum,data);
    }
    public static String getName(Integer businessType, JSONObject data)throws XbbException{
        return getName(XbbRefTypeEnum.getByCode(businessType),data);
    }
    public static String getName(List<Integer> businessTypes, JSONObject data)throws XbbException{
        if(CollectionsUtil.isEmpty(businessTypes)){
            return "";
        }
        return getName(businessTypes.get(0),data);
    }
    public static String getNameAttr(XbbRefTypeEnum xbbRefTypeEnum){
        String attr;
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                attr = CustomerManagementEnum.NAME.getAttr();
                break;
            case CONTACT:
                attr = ContactEnum.NAME.getAttr();
                break;
            case CUSTOMER_COMMUNICATE:
                attr = CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr();
                break;
            case CONTRACT:
                attr = ContractEnum.NAME.getAttr();
                break;
            case SALES_OPPORTUNITY:
                attr = SalesOpportunityEnum.NAME.getAttr();
                break;
            case REFUND:
                attr = RefundEnum.REFUND_NAME.getAttr();
                break;
            case QUOTATION:
                attr = QuotationEnum.NAME.getAttr();
                break;
            case COMMUNICATE_PLAN:
                attr = CommunicatePlanEnum.NAME.getAttr();
                break;
            case PRODUCT:
                attr = ProductEnum.NAME.getAttr();
                break;
            case PURCHASE:
                attr = PurchaseEnum.PURCHASE_NAME.getAttr();
                break;
            case SUPPLIER_CONTACT:
                attr = SupplierContactEnum.NAME.getAttr();
                break;
            case SUPPLIER_COMMUNICATE:
                attr = SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr();
                break;
            case RETURNED_PURCHASE:
                attr = ReturnedPurchaseEnum.PURCHASE_SHEET_ID_LINKED_TEXT.getAttr();
                break;
            case SUPPLIER:
                attr = SupplierEnum.SUPPLIER_NAME.getAttr();
                break;
            case BOM_BILL:
                attr = BomBillEnum.NAME.getAttr();
                break;
            case MARKET_ACTIVITY:
                attr = MarketActivityEnum.NAME.getAttr();
                break;
            case CLUE:
                attr = ClueEnum.COMPANY_NAME.getAttr();
                break;
            case COMPETITOR:
                attr = CompetitorEnum.NAME.getAttr();
                break;
            default:
                attr = null;
                break;
        }
        return attr;
    }
    public String getNameAttr(Integer businessType){
        return getNameAttr(XbbRefTypeEnum.getByCode(businessType));
    }
    public String getNameAttr(List<Integer> businessTypes){
        return getNameAttr(XbbRefTypeEnum.getByCode(businessTypes.get(0)));
    }

    /**
     * 归档操作
     * date: 2022/4/27 9:41 上午
     * @Author yingjf
     * @param archiveDTO:
     * @param list:
     * @param nameStr:
     * @param operateModuleType:
     * @param archived:
     */
    @Async("sysLogThreadPool")
    public void addOrDeleteArchive(ArchiveDTO archiveDTO,List<PaasFormDataEntityExt> list,String nameStr,OperateModuleTypeEnum operateModuleType,Integer archived
                        )throws XbbException{
        Integer saasMark = archiveDTO.getSaasMark();
        Integer businessType = archiveDTO.getBusinessType();
        ArchiveOperationLogHandle archiveLogHandle = operationLogFactory.getArchiveLogHandle(saasMark, businessType);
        OperateArchiveDTO operateArchiveDTO = new OperateArchiveDTO(archiveDTO,list,nameStr,operateModuleType,archived,archiveDTO.getIsBatch());
        archiveLogHandle.operate(operateArchiveDTO);
    }
    /**
     * 重载一下 便于直接调用
     * date: 2022/4/27 9:55 上午
     * @Author yingjf
     * @param businessTypes:
     */
    public String getOperateModuleName(List<Integer> businessTypes){
        return getOperateModule(XbbRefTypeEnum.getByCode(businessTypes.get(0))).getName();
    }
    /**
     * 重载一下 便于直接调用
     * date: 2022/4/27 9:55 上午
     * @Author yingjf
     * @param businessTypes:
     */
    public OperateModuleTypeEnum getOperateModule(List<Integer> businessTypes){
        return getOperateModule(XbbRefTypeEnum.getByCode(businessTypes.get(0)));
    }
    /**
     * 获取操作模块
     * date: 2022/4/27 9:53 上午
     * @Author yingjf
     * @param xbbRefTypeEnum:
     */
    public OperateModuleTypeEnum getOperateModule(XbbRefTypeEnum xbbRefTypeEnum){
        OperateModuleTypeEnum operateModuleType;
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                operateModuleType = OperateModuleTypeEnum.CUSTOMER;
                break;
            case QUOTATION:
                operateModuleType = OperateModuleTypeEnum.QUOTATION;
                break;
            case WORK_REPORT:
                operateModuleType = OperateModuleTypeEnum.WORKREPORT;
                break;
            case REFUND:
                operateModuleType = OperateModuleTypeEnum.REFUND;
                break;
            case SIGNIN:
                operateModuleType = OperateModuleTypeEnum.SIGNIN;
                break;
            case SALES_OPPORTUNITY:
                operateModuleType = OperateModuleTypeEnum.OPPORTUNITY;
                break;
            case CONTRACT:
                operateModuleType = OperateModuleTypeEnum.CONTRACT;
                break;
            case CUSTOMER_COMMUNICATE:
                operateModuleType = OperateModuleTypeEnum.CustomerCommunicate;
                break;
            case CONTACT:
                operateModuleType = OperateModuleTypeEnum.CONTACT;
                break;
            case COMMUNICATE_PLAN:
                operateModuleType = OperateModuleTypeEnum.CommunicatePlan;
                break;
            case COMPETITOR:
                operateModuleType = OperateModuleTypeEnum.COMPETITOR;
                break;
            case SERVICE_PROJECT:
                operateModuleType = OperateModuleTypeEnum.SERVICE_PROJECT;
                break;
            default:
                operateModuleType = null;
                break;
        }
        return operateModuleType;
    }
    /**
     * 更新访客计划日志
     * date: 2022/6/24 11:17 上午
     * @author yingjf
     * @param communicatePlanOperateDTO:
     * @param communicatePlanEntityExt:
     * @param oldCommunicatePlanEntityExt:
     */
    @Async("sysLogThreadPool")
    public void updateCommunicatePlanLog(CommunicatePlanOperateDTO communicatePlanOperateDTO,
                                         CommunicatePlanEntityExt communicatePlanEntityExt,CommunicatePlanEntityExt oldCommunicatePlanEntityExt){
        try {
            String operate = communicatePlanOperateDTO.getOperate();
            String userId = communicatePlanOperateDTO.getUserId();
            String loginUserName = communicatePlanOperateDTO.getLoginUserName();
            Long dataId = communicatePlanOperateDTO.getDataId();
            String communicatePlanName = FastJsonHelper.getStringOrDefaultFromFormData(communicatePlanEntityExt.getData(), CommunicatePlanEnum.NAME.getAttr(), "");
            UpdateVO updateVO = new UpdateVO();
            UserVO commitUser = new UserVO();
            commitUser.setName(loginUserName);
            commitUser.setUserId(communicatePlanOperateDTO.getUserId());
            updateVO.setUserVO(commitUser);
            updateVO.setPaasFormDataEntity(communicatePlanEntityExt);
            BeforeUpdateVO beforeUpdateVO = new BeforeUpdateVO();
            Long formId = communicatePlanEntityExt.getFormId();
            String corpid = communicatePlanEntityExt.getCorpid();
            PaasFormEntityExt paasFormEntityExt = (PaasFormEntityExt)proFormHelp.getPaasForm(formId, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), communicatePlanOperateDTO.getCorpid());
            beforeUpdateVO.setPaasFormEntityExt(paasFormEntityExt);
            beforeUpdateVO.setOldPaasFormData(oldCommunicatePlanEntityExt);
            PaasFormExplainEntity explain = paasFormExplainModel.getByFormId(formId, corpid);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explain.getExplains(), null);
            beforeUpdateVO.setExplainMap(explainMap);
            if(Objects.equals(operate, CommunicatePlanStatusEnum.CANCEL.getCode())){
                // 取消  用户“%s”取消了%s“%s”
                String memo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.LOG_MEMO_USER_CANCEL_WORK),
                        loginUserName, paasFormEntityExt.getName(), communicatePlanName);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.CommunicatePlan, OperateTypeEnum.ABOLISH,
                        dataId.toString(), communicatePlanName, memo, communicatePlanOperateDTO.getHttpHeader());
            }else{
                FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
                BeanUtil.copyProperties(communicatePlanOperateDTO,formDataUpdateDTO);
                OperationLogHandle operationLogHandle = operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(),XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
                UpdateOperationLogDTO UpdateOperationLogDTO = new UpdateOperationLogDTO(formDataUpdateDTO,
                        null,updateVO,beforeUpdateVO);
                operationLogHandle.update(UpdateOperationLogDTO);
            }
        }catch (XbbException e){
            log.error("com.xbongbong.paas.service.log.crm.help.OperationLogHelp.updateCommunicatePlanLog",e);
        }

    }
    /**
     * 跟新个人标签日志
     * date: 2022/6/24 11:17 上午
     * @author yingjf
     * @param personLabelSaveDTO:
     * @param personLabel:
     */
    @Async("sysLogThreadPool")
    public void updatePersonLableLog(PersonLabelSaveDTO personLabelSaveDTO,PersonLabelEntity personLabel){
        try{
            // 加编辑日志
            String corpid = personLabelSaveDTO.getCorpid();
            String userId = personLabelSaveDTO.getUserId();
            Integer refType = personLabelSaveDTO.getRefType();
            Integer refId = personLabelSaveDTO.getRefId();
            List<String> labelNameList = personLabelSaveDTO.getLabelNameList();
            String loginUserName = personLabelSaveDTO.getLoginUserName();
            JSONArray labelName = new JSONArray();
            if(personLabel!=null){
                labelName = personLabel.getLabelName();
            }
            String beforeStr = StringUtils.join(labelName, "、");
            String afterStr = StringUtils.join(labelNameList, "、");
            List<DetailLogPojo> detailArr = new ArrayList<>();
            detailArr.add(new DetailLogPojo(null, I18nMessageUtil.getMessage(I18nStringConstant.PERSON_LABLE), beforeStr,afterStr));
            PaasFormDataEntity paasFormDataEntityExt = proFormDataHelp.getFormData(corpid, Objects.equals(refType,0)?SaasMarkEnum.PAAS.getCode() : SaasMarkEnum.SAAS.getCode(), refType, refId.longValue());
            String name = getName(refType, paasFormDataEntityExt.getData());
            Long formId = paasFormDataEntityExt.getFormId();
            PaasFormEntity paasFormEntity = proFormHelp.getPaasForm(formId, refType, corpid);
            String memo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.LOG_MEMO_USER_UPDATE_PERSON_LABLE_WORK),
                    loginUserName, paasFormEntity.getName(), name);
            mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, loginUserName, getOperateModule(XbbRefTypeEnum.getByCode(refType)), OperateTypeEnum.EDIT, refId.toString(), name, memo, personLabelSaveDTO.getHttpHeader());
        }catch (XbbException e){
            log.error("com.xbongbong.paas.service.log.crm.help.OperationLogHelp.updatePersonLableLog",e);
        }

    }

    /**
     * 企业标签日志
     * date: 2022/6/24 11:20 上午
     * @author yingjf
     * @param addLabelDTO:
     * @param idIn:
     * @param beforePaasFormDataList:
     */
    @Async("sysLogThreadPool")
    public void handleLabelLog(AddLabelDTO addLabelDTO, List<Long> idIn,
                               List<PaasFormDataEntityExt> beforePaasFormDataList) {
        try {
            String corpid = addLabelDTO.getCorpid();
            Long formId = addLabelDTO.getFormId();
            Integer businessType = addLabelDTO.getBusinessType();
            String userId = addLabelDTO.getUserId();
            String loginUserName = addLabelDTO.getLoginUserName();
            String httpHeader = addLabelDTO.getHttpHeader();
            Integer saasMark = addLabelDTO.getSaasMark();
            OperateModuleTypeEnum  operateModuleTypeEnum = getOperateModule(XbbRefTypeEnum.getByCode(businessType));
            if(operateModuleTypeEnum==null){
                return;
            }
            // 这边需要再查一下  否则获取不到更新时间
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);
            List<PaasFormDataEntityExt> addBatchList = paasEsModel.getByIdList(idIn, corpid, saasMark, businessType, null,indexTypeEnum);
            Map<Long,PaasFormDataEntity> newDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(CollectionsUtil.isEmpty(addBatchList)||CollectionsUtil.isEmpty(beforePaasFormDataList)){
                return;
            }
            addBatchList.forEach(temp->{
                newDataMap.put(temp.getDataId(),temp);
            });
            List<DetailLogComplexPojo> detailArr = new ArrayList<>();
            PaasFormEntity paasFormEntity = proFormHelp.getPaasForm(formId, businessType, corpid);
            PaasFormExplainEntity explainEntity = proFormHelp.getExplainEntity(corpid, formId, businessType);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
            Set<Map.Entry<String, FieldAttrEntity>> entrySet = explainMap.entrySet();
            String labelAttr = null;
            String labelAttrName = null;
            for(Map.Entry<String, FieldAttrEntity> temp: entrySet){
                FieldAttrEntity fieldAttrEntity = temp.getValue();
                Integer fieldType = fieldAttrEntity.getFieldType();
                if(Objects.equals(FieldTypeEnum.LABEL.getType(),fieldType)){
                    labelAttr = fieldAttrEntity.getAttr();
                    labelAttrName = fieldAttrEntity.getAttrName();
                }
            }
            Set<Long> idSet = new HashSet<>();
            for(PaasFormDataEntity temp: addBatchList){
                List<Long> labelIdList= JSON.parseArray(JSON.toJSONString(temp.getData().get(labelAttr)), Long.class);
                if(labelIdList!=null){
                    idSet.addAll(labelIdList);
                }
            }
            for(PaasFormDataEntity temp: beforePaasFormDataList){
                List<Long> labelIdList= JSON.parseArray(JSON.toJSONString(temp.getData().get(labelAttr)), Long.class);
                if(labelIdList!=null){
                    idSet.addAll(labelIdList);
                }
            }
            Map<Long,String> labelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(CollectionsUtil.isNotEmpty(idSet)){
                List<LabelEntity> labelList = labelModel.getByLabelIds(idSet,corpid);
                labelList.forEach(temp->{
                    labelMap.put(temp.getId(),temp.getName());
                });
            }
            for(PaasFormDataEntity oldData: beforePaasFormDataList){
                Long dataId = oldData.getDataId();
                PaasFormDataEntity newData = newDataMap.get(dataId);
                List<Long> newDataLabelIdList= JSON.parseArray(JSON.toJSONString(newData.getData().get(labelAttr)), Long.class);
                List<Long> oldDataLabelIdList= JSON.parseArray(JSON.toJSONString(oldData.getData().get(labelAttr)), Long.class);
                String oldLabelNameStr = getLabelNameStr(labelMap, oldDataLabelIdList);
                String newLabelNameStr = getLabelNameStr(labelMap, newDataLabelIdList);
                List<DetailLogPojo> detailList = new ArrayList<>();
                if(!Objects.equals(oldLabelNameStr,newLabelNameStr)){
                    detailList.add(new DetailLogPojo(labelAttr, labelAttrName, oldLabelNameStr, newLabelNameStr));
                }
                String beforeTime = DateUtil.getString(oldData.getUpdateTime() * 1000L, DateUtil.SDFYMDHM);
                String afterTime = DateUtil.getString(newData.getUpdateTime()* 1000L, DateUtil.SDFYMDHM);
                if(!Objects.equals(beforeTime,afterTime)){
                    detailList.add(new DetailLogPojo(StringConstant.UPDATE_TIME, I18nMessageUtil.getMessage(CommonConstant.UPDATE_TIME), beforeTime,afterTime));
                }
                if(CollectionsUtil.isNotEmpty(detailList)){
                    String opObjectName = oldData.getData().getString(getNameAttr(businessType));
                    DetailLogComplexPojo detailLogPojo = new DetailLogComplexPojo(opObjectName, detailList);detailArr.add(detailLogPojo);
                }

            }
            String memo = "";
            Integer allowUpdateDataSize = detailArr.size();
            if(checkIsPublic(beforePaasFormDataList.get(0).getData(),businessType)){
                // 公海池批量编辑文案有区别 目前只有客户的
                memo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR_IN_PUBLIC), loginUserName, paasFormEntity.getName(),labelAttrName,allowUpdateDataSize);
            }else{
                memo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, paasFormEntity.getName(),labelAttrName,allowUpdateDataSize);
            }
            mongoLogHelp.buildLog4ComplexDetailArr(BasicConstant.TWO,detailArr, corpid, userId, loginUserName,  operateModuleTypeEnum, OperateTypeEnum.EDIT, "", "", memo, httpHeader);
        }catch (XbbException e){
            log.error("com.xbongbong.saas.help.LogHandleHelp.handleLabelLog",e);
        }
    }
    /**
     * 封装下标签名字符串
     * date: 2022/6/24 11:19 上午
     * @author yingjf
     * @param labelMap:
     * @param idList:
     */
    private String getLabelNameStr(Map<Long,String> labelMap,List<Long> idList){
        if(CollectionsUtil.isEmpty(idList)){
            return "";
        }else {
            List<String> nameList = new ArrayList<>();
            idList.forEach(temp->{ nameList.add(labelMap.get(temp)); });
            return  StringUtils.join(nameList, "、");
        }
    }
    /**
     * 校验是否在公海池
     * date: 2022/6/24 11:19 上午
     * @author yingjf
     * @param data:
     * @param businessType:
     */
    public static Boolean checkIsPublic(JSONObject data,Integer businessType) throws XbbException{
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        String isPublic = "";
        switch (xbbRefTypeEnum){
            case CUSTOMER_MANAGEMENT:
                isPublic = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), "");
                if(Objects.equals(PublicEnum.PUBLIC.getCode().toString(),isPublic)){
                    return true;
                }
            case CLUE:
                isPublic = FastJsonHelper.getStringOrDefaultFromFormData(data, ClueEnum.IS_PUBLIC.getAttr(), "");
                if(Objects.equals(PublicEnum.PUBLIC.getCode().toString(),isPublic)){
                    return true;
                }
            default:
                return false;
        }
    }

    /**
     * 访客计划完成的日志
     * date: 2022/8/5 11:06 上午
     * @author yingjf
     * @param :
     */
    @Async("sysLogThreadPool")
    public void finishCommunicatePlanLog(SaasFormSaveDTO saasFormSaveDTO, CommunicatePlanEntityExt oldCommunicatePlanEntityExt){
        try {
            String loginUserName = saasFormSaveDTO.getLoginUserName();
            String corpid = saasFormSaveDTO.getCorpid();
            String userId = saasFormSaveDTO.getUserId();
            String httpHeader = saasFormSaveDTO.getHttpHeader();
            Long dataId = oldCommunicatePlanEntityExt.getDataId();
            Long formId = oldCommunicatePlanEntityExt.getFormId();
            String communicatePlanName = FastJsonHelper.getStringOrDefaultFromFormData(oldCommunicatePlanEntityExt.getData(), CommunicatePlanEnum.NAME.getAttr(), "");
            PaasFormEntityExt paasFormEntityExt = (PaasFormEntityExt)proFormHelp.getPaasForm(formId, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), corpid);
            // 取消  用户“%s”取消了%s“%s”
            String memo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.LOG_MEMO_USER_FINISH_WORK),
                    loginUserName, paasFormEntityExt.getName(), communicatePlanName);
            mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.CommunicatePlan, OperateTypeEnum.FINISH,
                    dataId.toString(), communicatePlanName, memo, httpHeader);
        }catch (XbbException e){
            log.error("com.xbongbong.paas.service.log.crm.help.OperationLogHelp.finishCommunicatePlan",e);
        }
    }

    /**
     * 移动端修改状态
     * date: 2022/8/8 3:27 下午
     * @author yingjf
     * @param :
     */
    @Async("sysLogThreadPool")
    public void changeStatusLog(ChangeStatusDTO changeStatusDTO, PaasFormDataEntityExt paasFormDataEntityExt,Long newUpdateTime){
        try{
            String userName = changeStatusDTO.getLoginUserName();
            String corpid = changeStatusDTO.getCorpid();
            String userId = changeStatusDTO.getUserId();
            Integer businessType = changeStatusDTO.getBusinessType();
            JSONObject data = paasFormDataEntityExt.getData();
            Long dataId = paasFormDataEntityExt.getDataId();
            Long oldUpdateTime = paasFormDataEntityExt.getUpdateTime();
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(changeStatusDTO.getBusinessType());
            String attr = null;
            switch (redundantTemplateTypeEnum) {
                case CUSTOMER:
                    attr = CustomerManagementEnum.TYPE.getAttr();
                    break;
                case CONTRACT:
                    attr = ContractEnum.STATUS.getAttr();
                    break;
                case QUOTATION:
                    attr = QuotationEnum.STATUS.getAttr();
                    break;
                default:
                    return;
            }
            OperateModuleTypeEnum operateModuleType = getOperateModule(XbbRefTypeEnum.getByCode(businessType));
            String opObjectName = getName(businessType, data);
            Long formId = paasFormDataEntityExt.getFormId();
            PaasFormEntity paasFormEntity = proFormHelp.getPaasForm(formId, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), corpid);
            PaasFormExplainEntity explainEntity = proFormHelp.getExplainEntity(corpid, formId, businessType);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);


            FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
            List<ItemPoJo> items = fieldAttrEntity.getItems();
            String attrName = fieldAttrEntity.getAttrName();
            Map<String,String> itemsMap = new HashMap<>();
            items.forEach(temp->{
                String value = (String)temp.getValue();
                String text = temp.getText();
                itemsMap.put(value,text);
            });
            String oldType = FastJsonHelper.getStringOrDefaultFromFormData(data, attr, "");
            String newType = changeStatusDTO.getType();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_WORK), userName, paasFormEntity.getName(), opObjectName);
            List<DetailLogPojo> detailLogPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            detailLogPojoList.add(new DetailLogPojo(attr,attrName,itemsMap.get(oldType),itemsMap.get(newType)));
            SimpleDateFormat SDF = new SimpleDateFormat(DateTimeEnum.DATETIME.getType());
            String updataBefore = "";
            String updataAfter =  "";
            if (oldUpdateTime > 0) {
                updataBefore = DateTimeUtil.getStringEpochSecond(oldUpdateTime, SDF);
            }
            if (newUpdateTime > 0) {
                updataAfter = DateTimeUtil.getStringEpochSecond(newUpdateTime, SDF);
            }
            if(!Objects.equals(updataBefore,updataAfter)){
                detailLogPojoList.add(new DetailLogPojo("updateTime",I18nMessageUtil.getMessage(CommonConstant.UPDATE_TIME), updataBefore,updataAfter));
            }
            mongoLogHelp.buildLog4DetailArr(detailLogPojoList, corpid, userId, userName,
                    operateModuleType, OperateTypeEnum.EDIT, dataId.toString(), opObjectName, memo, changeStatusDTO.getHttpHeader());
        }catch (Exception e){
            log.error("com.xbongbong.paas.service.log.crm.help.OperationLogHelp.changeStatusLog",e);
        }
    }


}
